import axios from 'axios'
import {Message} from 'element-ui'
import router from '../router'
import {removeToken} from '@/utils/token'

// 创建一个axios实例
const service = axios.create({
  baseURL: process.env.BASE_URL,
  timeout: 600000
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    console.log(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    let code = response.data.code;
    if (code === 0) { // 请求成功
      return response.data;
    }
    // 如果code!=0, 则抛出错误
    throw new Error(response.data.msg);
  },
  error => {
    console.log(error);
    let response = error.response;
    let code = error.response.data.code;

    if (code === 1001) { // 参数有误
      errorMsg(response.data.msg);
    }
    if (code === 1002) { // 请求错误
      errorMsg('请求错误，请联系管理员');
    }
    if (code === 1003) { // 需要登录
      if (response.config.url !== '/logout') {
        errorMsg('登录过期，请重新登录');
      }
      removeToken();
      router.push('/login');
    }
    if (code === 1004) { // 无权限
      errorMsg('无权限操作');
    }
    if (code === -1) { // 未知异常
      errorMsg('系统错误,请联系管理员');
    } else {
      // 其他返回码信息
      errorMsg(response.data.msg);
    }
    return Promise.reject(error);
  }
);

function errorMsg (msg) {
  Message({
    message: msg,
    type: 'error'
  });
}

export default service;
